14. How Java Loads Classes
How Java Loads Classes
In this section, you'll learn about how Java loads classes, and you'll use a custom class loader to load class byte code.
ND079 JPND C2 L04 A13 How Java Loads Classes
Java Program Lifecycle
Before we get into the details of class loaders, let's brush up on these terms by reviewing the basic lifecycle of developing and executing a Java program.
Basic Lifecycle
- You start by writing Java source code, which is human-readable text.
- The Java compiler, or the
javac
command, compiles the source code into bytecode. Bytecode is Java's platform-independent representation of the classes in the program. - The Java launcher, or the
java
command, starts up the Java Virtual Machine, and loads the bytecode to execute the program.
SOLUTION:
Byte code can execute on any Java Virtual Machine.Where Java Looks for Bytecode
Class bytecode is stored in files, such as .class
files, .jar
files, or .zip
files. The Java launcher needs to find these files. Here are the different ways the Java launcher looks for them:
- Looks in the lhe local file system for the Java Runtime Installation, which contains Bootstrap Classes, like
java.lang.Object
andjava.lang.String
. The location of the installation comes from theJAVA_HOME
environment variable. - Looks for user-defined classes in the current directory where the
java
command is running. - Follows the
CLASSPATH
environment variable. - Follows the
-classpath
or-jar
options passed to thejava
command on the command-line.
SOLUTION:
- The current directory where the Java program is running.
- Files pointed to by the `CLASSPATH` environment variable.
- The value of the `-classpath` (or `-cp`) option passed to the `java` command.
- The value of the `-jar` option passed to the `java` command.
Class Loaders
Every class in the Java Runtime is loaded by a ClassLoader
.
The input to a ClassLoader
is the name of the class to be loaded, and the output is the Class
object representing that class:
The ClassLoader
tries to locate the bytecode of the class (similarly to how the Java launcher loads bytecode — described above), and then creates an instance of the corresponding Class
object.